import $ from '../jquery-3.4.1.min.js';
import ajax from '../utils/ajax';
renderOutPack();
//点击全选
$('#outPackAllChoose').click(function () {
    const value = document.querySelector('#outPackAllChoose');
    const inputs = document.querySelectorAll("#outPackTbody [index]");
    if (value.checked) {
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].checked = true;
        }
    } else {
        for (let i = 0; i < inputs.length; i++) {
            inputs[i].checked = false;
        }
    }
})
//点击确认出库
$('.outPackSure').click(async function () {
    addOutPack();

})
//点击删除返回入库
$("#outPackTbody1").on('click', '.outPackDel', function () {
    const isRun = confirm("是否删除");
    if (isRun) {
        const _id = $(this).attr("index");
        delOutPack(_id);
    }

})

//确认出库
function addOutPack() {
    const inputs = $("#outPackTbody [type=checkbox]:checked");
    const arr = [];//物料清单的id
    const arr1 = [];//入库的id,可能会有重复
    for (let i = 0; i < inputs.length; i++) {
        arr.push(inputs[i].getAttribute("index1"));
        arr1.push(inputs[i].getAttribute("index"));
    }
    const arr2 = [...new Set(arr1)];//去重后的入库的id
    ajax({
        url: '/outPack/addOutPack',
        type: 'post',
        data: {
            arr, arr2
        },
        success(res) {
            if (res.code == 200) {
                alert("出库成功");
                renderOutPack();
                $('.addThing').addClass("active");
            }
        }
    })

}
//获取所有的出库了的数据
function getOutPack() {
    return new Promise((resolve, reject) => {
        ajax({
            url: '/outPack/getOutPack',
            type: 'post',
            success(res) {
                resolve(res)
            }
        })
    })

}
//渲染出库列表在首页
async function renderOutPack() {
    const { result } = await getOutPack();
    if (result) {
        const html = result.map((item, index) =>
            `
            <tr>
                <td class='outPackThingName'>${item.thingName}</td>
                <td class='outPackThingBrand'>${item.thingBrand}</td>
                <td class='outPackJoinPackName'>${item.joinPackName}</td>
                <td class='outPackJoinPackMaterial'>${item.joinPackMaterial}</td>
                <td class='outPackThingType'>${item.thingType}</td>
                <td class='outPackThingUnit'>${item.thingUnit}</td>
                <td class='outPackThingNote'>${item.thingNote}</td>
                <td class='outPackSet'><span class='outPackDel' index='${item._id}'>删除</span></td>
            </tr>
            `
        ).join("");
        $('#outPackTbody1').html(html);
    }
}
//删除出库,返回入库
function delOutPack(_id) {
    ajax({
        url: '/outPack/delOutPack',
        type: 'post',
        data: {
            _id
        },
        success(res) {
            if (res.code == 200) {
                alert('删除成功');
            } else {
                alert('删除失败');
            }
        }
    })
}


